package esa.android;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TableRow;
import android.widget.TextView;
import esa.android.JSONDataFetchers.JSONDataFetchersContext;

public class LunchmenuandroidActivity extends AbstractAndroidApplication {
	private static final int DIALOG_SETTINGS_ID = 1;
	private static final int DIALOG_PROGRESS_ID = 2;
	private static final int DIALOG_MESSAGE_ID = 3;
	private static final int DIALOG_ABOUT_ID = 4;
	
	private static final String SELECTED_PLACES_PREFERENCE_KEY = "selected_places";
	private static final String BUNDLE_CONTENT_KEY="content";
	private static final String BUNDLE_CONTENT_KEY2="content2";

	protected AsyncTask<?, ?, ?> runningTask =null;
	
	@Override
	protected void startApplication() {

		JSONDataFetchersContext c = new JSONDataFetchersContext() {

			@Override
			public void showProgressDialog(int messageId) {
				if (messageId>0) {
					showProgressDialogAsked(R.string.loading_in_progress, messageId);
				}
				else {
					showProgressDialogAsked(R.string.loading_in_progress);
				}
			}

			@Override
			public void showErrorDialog() {
				showMessageDialogAsked(R.string.loading_error);
			}

			@Override
			public void hideProgressDialog() {
				try {
					removeDialog(DIALOG_PROGRESS_ID);
				} catch (IllegalArgumentException e) {

				}

			}

			@Override
			public void showMessage(int messageId) {
				if (messageId>0) {
					setTitle(getResources().getString(R.string.app_name)+" - "+getResources().getString(messageId));
				}
			}
		};

		JSONDataFetchers.initialize(c);

		showMainContentAsked();
	}




	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i("LunchMenu", "options selected: " + item.getItemId());
		switch (item.getItemId()) {
		case R.id.item1:
			showSettingsDialogAsked();
			return true;
		case R.id.item2:
			showAboutDialogAsked();
			return true;
		case R.id.item3:
			showMainContentAsked();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle bundle) {
		Dialog dialog = null;
		if (id == DIALOG_SETTINGS_ID) {
			String[] places = bundle.getStringArray(BUNDLE_CONTENT_KEY);
			String[] placeIds = bundle.getStringArray(BUNDLE_CONTENT_KEY2);
			dialog = createSettingsDialog(places, placeIds);
		} else if (id == DIALOG_MESSAGE_ID) {
			String message = bundle.getString(BUNDLE_CONTENT_KEY);
			dialog = createMessageDialog(message);
		} else if (id == DIALOG_ABOUT_ID) {
			String message = bundle.getString(BUNDLE_CONTENT_KEY);
			dialog = createMessageDialog(message);
		} else if (id == DIALOG_PROGRESS_ID) {
			String message = bundle.getString(BUNDLE_CONTENT_KEY);
			dialog = createProgressDialog(message);
			
		}
		return dialog;
	}

	protected Dialog createSettingsDialog(final String[] places, final String[] placeIds) {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.select_places);
		builder.setCancelable(true);

		builder.setMultiChoiceItems(places, getPreselected(placeIds),
				new DialogInterface.OnMultiChoiceClickListener() {
					public void onClick(DialogInterface dialog, int item,
							boolean isChecked) {
						((AlertDialog) dialog).getListView().setItemChecked(0,false);

					}
				});

		builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				Log.i("LunchMenu", "saving settings dialog");
				Collection<String> selectedPlaces = new ArrayList<String>();
				ListView list = ((AlertDialog) dialog).getListView();
				SparseBooleanArray selected = list.getCheckedItemPositions();

				for (int i = 0; i < selected.size(); i++) {
					int key = selected.keyAt(i);
					if (selected.get(key) == true) {
						selectedPlaces.add(placeIds[key]);

					}
				}
				
				settingsDialogSaveAsked(selectedPlaces);
			}

		});
		AlertDialog dialog = builder.create();

		return dialog;
	}

	private boolean [] getPreselected(String [] places) {
		boolean [] selected = new boolean [places.length];
		Collection<String> selectedPlaces = (Collection<String>) preferences.getData(SELECTED_PLACES_PREFERENCE_KEY, new ArrayList<String>());
		for (int i = 0; i < selected.length; i++) {
			selected[i]=selectedPlaces.contains(places [i]);
		}
		return selected;
	}
	
	protected Dialog createMessageDialog(final String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message).setCancelable(false).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog dialog = builder.create();
		return dialog;
	}

	protected Dialog createProgressDialog(final String message) {
		return ProgressDialog.show(this, "", message, true,  true,new DialogInterface.OnCancelListener(){
            @Override
            public void onCancel(DialogInterface dialog) {
            	Log.i("LunchMenu", "loading cancelled");
            	cancelRunningTask();
            }
        } );
	}
	
	protected void cancelRunningTask() {
    	if(runningTask!=null && !runningTask.isCancelled()) {
    		runningTask.cancel(true);            		
    	}		
	}


	protected void settingsDialogSaveAsked(Collection<String> selectedPlaceIds) {
		preferences.putData(SELECTED_PLACES_PREFERENCE_KEY, selectedPlaceIds);

		removeDialog(DIALOG_SETTINGS_ID);

		showMainContentAsked();
	}

	protected void showMainContentAsked() {

		Collection<String> selectedPlaces = (Collection<String>) preferences.getData(SELECTED_PLACES_PREFERENCE_KEY, new ArrayList<String>());

		Log.i("LunchMenu", "starting show menu");
		
		cancelRunningTask();
		
		runningTask = new JSONDataFetchers.FetchLunchData() {
			protected void updateUI(Collection<Map<String, Object>> dayMenus) {

				TableLayout tl = (TableLayout) findViewById(R.id.tableLayout1);
				tl.removeAllViews();
				for (Map<String, Object> dayMenu : dayMenus) {

					TableRow tr = new TableRow(LunchmenuandroidActivity.this);
					TextView textView = new TextView(LunchmenuandroidActivity.this);
					tr.setBackgroundColor(Color.DKGRAY);
					textView.setTextColor(Color.WHITE);
					textView.setText(dayMenu.get("name").toString());
					Typeface boldTypeface = Typeface.DEFAULT_BOLD;
					textView.setTypeface(boldTypeface);
					textView.setPadding(4, 2, 4, 2);

					tr.addView(textView);
					
					Object hp = dayMenu.get("homePageUrl");
					if (hp!=null) {
						final String homePageUrl = hp.toString();

						Button homePageButton = new Button(LunchmenuandroidActivity.this); 
						homePageButton.setText("www"); 
				        homePageButton.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(homePageUrl));
								startActivity(i);
							
							}
						});
						
						tr.addView(homePageButton);
					}
					
					
					Object latitude = dayMenu.get("latitude");
					Object longitude = dayMenu.get("longitude");
					if (latitude !=null && longitude!=null) {

						Button navigateButton = new Button(LunchmenuandroidActivity.this); 
						navigateButton.setText("map"); 
				        navigateButton.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
							
							}
						});
						
						tr.addView(navigateButton);
					}
					
					tl.addView(tr,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
					TableRow.LayoutParams layout = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					layout.span=2;
					Collection<String> menuEntries = (Collection<String>) dayMenu.get("menuEntries");
					for (String menuEntry : menuEntries) {
						TableRow trE = new TableRow(
								LunchmenuandroidActivity.this);
						TextView tv = new TextView(LunchmenuandroidActivity.this);
						tv.setPadding(2, 2, 2, 2);
						tv.setText(menuEntry);
						
						trE.addView(tv,layout);
						tl.addView(trE);

					}

				}

			}
		}.execute(selectedPlaces);
	}

	protected void showSettingsDialogAsked() {
		Log.i("LunchMenu", "starting settings dialog");
		
		cancelRunningTask();
		
		runningTask = new JSONDataFetchers.FetchPlacesData() {
			protected void updateUI(Collection<Map<String, Object>> places) {
				Bundle b = new Bundle();
				Collection<String> placeNames = new ArrayList<String>();
				Collection<String> placeIds = new ArrayList<String>();
				for (Map<String, Object> p : places) {
					placeNames.add(p.get("name").toString());
					placeIds.add(p.get("placeId").toString());
				}
				b.putStringArray(BUNDLE_CONTENT_KEY,placeNames.toArray(new String[placeNames.size()]));
				b.putStringArray(BUNDLE_CONTENT_KEY2,placeIds.toArray(new String[placeIds.size()]));

				showDialog(DIALOG_SETTINGS_ID, b);
			}
		}.execute();
	}

	protected void showAboutDialogAsked() {
		Bundle b = new Bundle();
		b.putString(BUNDLE_CONTENT_KEY, getApplicationVersionInfo());
		showDialog(DIALOG_ABOUT_ID, b);
	}
	
	protected void showMessageDialogAsked(int textId) {
		Bundle b = new Bundle();
		b.putString(BUNDLE_CONTENT_KEY, getResources().getString(textId));
		showDialog(DIALOG_MESSAGE_ID, b);
		
	}

	protected void showProgressDialogAsked(int ...textIds) {
		Bundle b = new Bundle();
		StringBuilder sb = new StringBuilder();
		for (int i: textIds) {
			if (sb.length()>0) sb.append("\n");
			sb.append(getResources().getString(i));
		}
		b.putString(BUNDLE_CONTENT_KEY, sb.toString());
		showDialog(DIALOG_PROGRESS_ID, b);
		
	}

}